import get from 'lodash-es/get.js';
import PolygonLayer from '../../../components/gis-map/js/PolygonLayer.js';
import { getPlugins } from '@gis/lib/components/AMap/js/AMapUtils.js';
import { bdToGd } from '../../../components/gis-map/js/translator.js';
import { getRegionCoordinate, getYardRegionCoordinate } from '@gis/lib/api';
import { useUserInfoStore } from '@gis/lib/pinia/userInfo.js';
import { handleCommonResult } from '@gis/lib/utils/resolver.js';

function formatPathData(data = {}) {
  if (typeof data !== 'object' || !data) return;
  if (data.Q && data.R) return [data.R, data.Q];
  if (data.lng && data.lat) return [data.lng, data.lat];
  if (data.longitude && data.latitude) return [data.longitude, data.latitude];
}

function isReginGroupEmpty(list, key = 'regin_group') {
  return !list || !list.length || list.every((item) => !item[key] || !item[key].length);
}

export default {
  name: 'map-command-dispatching-polygon',
  render() {
    return null;
  },
  props: {
    autoDistrictSearch: { type: Boolean, default: true },
  },
  setup() {
    const userInfoStore = useUserInfoStore();
    return { userInfoStore };
  },
  computed: {
    area_code() {
      return this.userInfoStore.area_code;
    },
    area_name() {
      return this.userInfoStore.area_name;
    },
    yard_id() {
      return get(this.userInfoStore, 'userData.yardId');
    },
  },
  async created() {
    this.AMap = this.$attrs.AMap;
    this.map = this.$attrs.map;

    await this.getDataAsync();
  },
  unmounted() {},
  beforeDestroy() {},
  methods: {
    async getDataAsync() {
      await Promise.all([this.getAreaAsync(), this.getYardArea()]);
      this.map.setFitView(this.areaLayer.layer.getOverlays(), true, [0, 0, 0, 400]);
    },
    async getAreaAsync() {
      const data = await this.getRegionAsync(async () => {
        const params = {
          area_code: this.area_code,
          is_contain_oneself: 1,
          range_type: 6,
        };
        const data = handleCommonResult(await getRegionCoordinate(params).catch(() => {}));
        return !isReginGroupEmpty(data, 'coordinate') ? data : null;
      }, this.autoDistrictSearch);

      if (!this.areaLayer) {
        this.areaLayer = new PolygonLayer({
          AMap: this.AMap,
          map: this.map,
        });
      }
      this.areaLayer.render(data);
    },
    async getYardArea() {
      if (!this.yard_id) return;
      let data = this.handleCommonResult(await getYardRegionCoordinate(this.yard_id));
      data = data.map((item) => {
        const coordinate = item.coordinate || [];
        return {
          center: [],
          path: coordinate.map((item) => bdToGd(item.lng, item.lat)),
        };
      });
      // if (!this.yardLayer) {
      //   this.yardLayer = new PolygonLayer({
      //     map: this.map,
      //     label: { show: true },
      //   });
      // }
      // this.yardLayer.render(data);
    },
    async getRegionAsync(api, autoDistrictSearch) {
      const data = await api();
      if (data && data.length) {
        return data.map((item) => {
          return Object.assign(item, {
            center: bdToGd.apply(null, [item.longitude, item.latitude]),
            path: item.coordinate.map((subitem) => bdToGd.apply(null, formatPathData(subitem))).filter(Boolean),
          });
        });
      } else if (autoDistrictSearch === true) {
        return await new Promise((resolve) => {
          this.getPathByDistrictSearch(this.area_name, 'district').then((searchData) => {
            const areaRegion = searchData.boundaries.map((path) => ({
              path,
            }));
            console.log('autoDistrictSearch area region: ', areaRegion);
            resolve(areaRegion);
          });
        });
      }
    },
    async getPathByDistrictSearch(area_name, level = 'province') {
      if (!this.district) {
        this.district = await getPlugins('DistrictSearch', {
          subdistrict: 1, //获取边界不需要返回下级行政区
          extensions: 'all', //返回行政区边界坐标组等具体信息
          level: level, //查询行政级别为 country：国家,province：省/直辖市,city：市,district：区/县,biz_area：商圈
        });
      }
      return await new Promise((resolve) => {
        this.district.setLevel(level);
        this.district.search(area_name, (status, result) => {
          const list = result ? result.districtList || [] : [];
          const res = typeof list[0] === 'object' && list[0] ? list[0] : {};
          resolve({
            boundaries: res.boundaries || [],
            districtList: res.districtList || [],
          });
        });
      });
    },
  },
};
